import React, {forwardRef, useEffect, useImperativeHandle, useState} from "react";
import { Button, Modal, Space, Table, TableColumnType, message } from "antd";
import { companyTypes  } from "@/constants/types";
import { customerCertifyCheck, fetchCompanyList, updateCompany, startCooperation, cancelCooperation, restartCooperation, uploadContract, updateStaffs } from "../services";
import { calculateTableWidth } from "@/utils/util";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import CompanyUpdate from "../modals/CompanyUpdate";
import { useRequest } from "ahooks";
import { history } from "@umijs/max";
import CompanyCertify from "../modals/CompanyCertify";
import {isCooperationTodo, isCooperationCancel, isCooperationDone} from "@/utils/dictUtil";
import ContractUpload from "../modals/ContractUpload";
import CompanyPhoneManage from "../modals/CompanyPhoneManage";

interface tabProps {
  searchValue: any;
  activeKey: string;
  tabKey: string,
  refreshNum: Function
}
const CompanyListTable = forwardRef(({searchValue = {}, activeKey, tabKey, refreshNum}: tabProps, ref) => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 10,
    total: 0
  });

  // 操作
  const [currentRow, setCurrentRow] = useState<companyTypes | null>(null);
  /* 编辑 */
  const [visible, setVisible] = useState<boolean>(false);
  const {loading: updateLoading, runAsync: updateCompanyApi} = useRequest(updateCompany, {manual: true});
  /* 认证 */
  const [certifyVisible, setCertifyVisible] = useState<boolean>(false);
  const {loading: certifyLoading, runAsync: certifyCompanyApi} = useRequest(customerCertifyCheck, {manual: true});
  /* 上传 */
  const [uploadVisible, setUploadVisible] = useState(false);
  const {loading: uploadLoading, runAsync: uploadContractApi} = useRequest(uploadContract, {manual: true});
  /* 下单手机 */
  const [updateStaffsVisible, setUpdateStaffsVisible] = useState(false);
  const {loading: updateStaffsLoading, runAsync: updateStaffsApi} = useRequest(updateStaffs, {manual: true});



  const search = async (params:{pageNum: number; pageSize: number} = {
    pageNum: 1,
    pageSize: 10
  }) => {
    const checkStatusMaps: any = {
      noAuth: '0',
      checkingNum: '2',
      authed: '1'
    }
    const res = await fetchCompanyList({
      ...searchValue,
      ...params,
      checkStatus: checkStatusMaps?.[activeKey]
    });
    setDataSource(res?.data || []);
    setPagination({
      ...params,
      current: params.pageNum,
      total: res?.total
    });
  }


  const refreshTable = () => {
    if (activeKey !== tabKey) {
      return ;
    }
    search({
      pageNum: 1,
      pageSize: pagination.pageSize
    });
  }

  // 编辑客户
  const companyUpdateProps = {
    visible,
    title: '编辑客户',
    currentRow,
    loading: updateLoading,
    onCancel: () => {
      setCurrentRow(null);
      setVisible(false);
    },
    onSubmit: async (params: companyTypes) => {
      const res = await updateCompanyApi(params);
      if (res?.code === '0') {
        companyUpdateProps.onCancel();
        search({
          pageNum: 1,
          pageSize: pagination.pageSize
        });
        refreshNum();
      }
    }
  }
  // 客户认证
  const companyCertifyProps = {
    visible: certifyVisible,
    title: '客户认证',
    currentRow,
    loading: certifyLoading,
    onCancel: () => {
      setCurrentRow(null);
      setCertifyVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await certifyCompanyApi(params);
      if (res?.code === '0') {
        companyCertifyProps.onCancel();
        message.success(res?.msg);
        search({
          pageNum: 1,
          pageSize: pagination.pageSize
        });
        refreshNum();
      }
    }
  }
  // 上传合同
  const updateStaffsProps = {
    visible: updateStaffsVisible,
    title: '可下单手机管理',
    currentRow,
    loading: updateStaffsLoading,
    onCancel: () => {
      setCurrentRow(null);
      setUpdateStaffsVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await updateStaffsApi(params);
      if (res?.code === '0') {
        updateStaffsProps.onCancel();
        message.success('上传成功!');
        search({
          pageNum: 1,
          pageSize: pagination.pageSize
        });
      }
    }
  }

  // 下单手机
  const contractProps = {
    visible: uploadVisible,
    title: '上传合同',
    currentRow,
    loading: uploadLoading,
    onCancel: () => {
      setCurrentRow(null);
      setUploadVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await uploadContractApi(params);
      if (res?.code === '0') {
        contractProps.onCancel();
        message.success('上传成功!');
        search({
          pageNum: 1,
          pageSize: pagination.pageSize
        });
      }
    }
  }

  const handleEdit = (record: companyTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  const handleView = (record: companyTypes) => {
    history.push(`/company-manage/company-deatil?id=${record?.id}`);
  }
  const handleCertify = (record: companyTypes) => {
    setCurrentRow(record);
    setCertifyVisible(true);
  }
  const handleUploadContract = (record: companyTypes) => {
    setCurrentRow(record);
    setUploadVisible(true);
  }
  const handlePhoneManage = (record: companyTypes) => {
    setCurrentRow(record);
    setUpdateStaffsVisible(true);
  }


  const startCoop = (record: companyTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定开启合作？',
      onOk: () => {
        startCooperation({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              refreshTable();
            }
          }
        )
      }
    });
  }
  const stopCoop = (record: companyTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定取消合作？',
      onOk: () => {
        cancelCooperation({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              refreshTable();
            }
          }
        )
      }
    });
  }
  const restartCoop = (record: companyTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定重新开启合作？',
      onOk: () => {
        restartCooperation({id: record?.id}).then(
          res => {
            if (res?.code === '0') {
              refreshTable();
            }
          }
        )
      }
    });
  }


  useImperativeHandle(ref, () => ({
    refreshTable
  }));


  useEffect(() => {
    if (tabKey === activeKey) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      });
    }
  }, [tabKey, activeKey]);


  const noAuthColumns: TableColumnType<companyTypes> [] = [
    {
      title: '状态',
      dataIndex: 'checkStatus',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="customerCheckStatus" value={record?.checkStatus} />
    },
    {
      title: '客户编码',
      dataIndex: 'code',
      width: 120
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="customType" value={record?.type} />
    },
    {
      title: '属性',
      dataIndex: 'category',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="customerAttr" value={record?.category} />
    },
    {
      title: '公司简称',
      dataIndex: 'nickName',
      ellipsis: true,
      width: 180
    },
    {
      title: '联系人',
      dataIndex: 'contacts',
      width: 120
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      width: 150
    },
    {
      title: '主账号',
      dataIndex: 'mainAccount',
      width: 120
    },
    {
      title: '结算方式',
      dataIndex: 'settlement',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="settlement" value={record?.settlementMethod} />
    },
    {
      title: '所属销售',
      dataIndex: 'salesName',
      width: 120
    },
    {
      title: '渠道',
      dataIndex: 'channel',
      width: 120
    },
    {
      title: '来源',
      dataIndex: 'source',
      ellipsis: true,
      width: 150
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: 150
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: 180
    },
    {
      title: '操作',
      dataIndex: 'options',
      fixed: 'right',
      width: 280,
      render: (_, record) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleView(record)}>查看详情</Button>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleCertify(record)}>认证</Button>
          </Space>
        );
      }
    }
  ];

  const authedColumns: TableColumnType<companyTypes> [] = [
    {
      title: '状态',
      dataIndex: 'checkStatus',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="customerCheckStatus" value={record?.checkStatus} />
    },
    {
      title: '合作状态',
      dataIndex: 'checkStatus',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="cooperationStatus" value={record?.cooperationStatus} />
    },
    {
      title: '客户编码',
      dataIndex: 'code',
      width: 120
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="customType" value={record?.type} />
    },
    {
      title: '属性',
      dataIndex: 'category',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="customerAttr" value={record?.category} />
    },
    {
      title: '公司简称',
      dataIndex: 'nickName',
      width: 120
    },
    {
      title: '联系人',
      dataIndex: 'contacts',
      width: 120
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      width: 150
    },
    {
      title: '主账号',
      dataIndex: 'mainAccount',
      width: 120
    },
    {
      title: '结算方式',
      dataIndex: 'settlement',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="settlement" value={record?.settlementMethod} />
    },
    {
      title: '所属销售',
      dataIndex: 'salesName',
      width: 120
    },
    {
      title: '渠道',
      dataIndex: 'channel',
      width: 120
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: 150
    },
    {
      title: '认证时间',
      dataIndex: 'checkTime',
      ellipsis: true,
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'options',
      fixed: 'right',
      width: 380,
      render: (_, record) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleView(record)}>查看详情</Button>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            {isCooperationTodo(record?.cooperationStatus) && <Button type="link" onClick={() => startCoop(record)}>开启合作</Button>}
            {isCooperationDone(record?.cooperationStatus) && <Button type="link" onClick={() => stopCoop(record)}>取消合作</Button>}
            {isCooperationDone(record?.cooperationStatus) && <Button type="link" onClick={() => handlePhoneManage(record)}>下单手机</Button>}
            {isCooperationCancel(record?.cooperationStatus) && <Button type="link" onClick={() => restartCoop(record)}>重新合作</Button>}
            {(isCooperationTodo(record?.cooperationStatus) || isCooperationCancel(record?.cooperationStatus)) && <Button type="link" onClick={() => handleUploadContract(record)}>上传合同</Button>}
          </Space>
        );
      }
    }
  ];

  const columns = activeKey === 'authed' ? authedColumns : noAuthColumns

  return (
    <>
      <Table
         bordered
         rowKey="id"
         dataSource={dataSource}
         columns={columns}
         scroll={{x: calculateTableWidth(columns), y: 610}}
         pagination= {{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            search({pageNum, pageSize});
          }
         }}
      /> 
      {visible && <CompanyUpdate {...companyUpdateProps} />}
      {certifyVisible && <CompanyCertify {...companyCertifyProps} />}
      {uploadVisible && <ContractUpload {...contractProps} />}
      {updateStaffsVisible && <CompanyPhoneManage {...updateStaffsProps} />}
    </>
  );
});


export default CompanyListTable;